$(document).ready(function () {
	var permissions = {};
	
    var icon = "<i class='fa fa-times-circle'></i> ";
    $("#signupForm").validate({
        rules : {
            name : {required : true,}
        },
        messages : {
            name : {required : icon + "请输入名称"}
        }
    });
    
    if($("input[name='permissionStatus']:checked").val() == '2'){
    	$("#permission-content").css("display", "block");
    }
    
    $(":radio").click(function(){
    	if($(this).val() == '2'){
    		$("#permission-content").css("display", "block");
    	} else {
    		$("#permission-content").css("display", "none");
    	}
    });
    
	if($("input[name='permissionUserNames']").val().length > 0 || $("input[name='permissionTagNames']").val().length > 0 || $("input[name='permissionOrgNames']").val().length > 0){
		$('#permissionEdit').css("display", "inline-block");
		$('#permissionAdd').css("display", "none");
	} else {
		$('#permissionAdd').css("display", "block");
		$('#permissionEdit').css("display", "none");
	}
	
	for(let key of $("input[name='permissionUserNames']").val().split(',')) {
		$('#permissionContent').append(createElement(key, "2"));
	}
	for(let key of $("input[name='permissionTagNames']").val().split(',')) {
		$('#permissionContent').append(createElement(key, "1"));
	}
	for(let key of $("input[name='permissionOrgNames']").val().split(',')) {
		$('#permissionContent').append(createElement(key, "0"));
	}
});
$.validator.setDefaults({
	submitHandler : function() {
        $.ajax({
            cache : false,
            type : "POST",
            url : ctx + "a/permission/update",
            data : $('#signupForm').serialize(),// 你的formid
            async : false,
            error : function(request) {parent.layer.alert("Connection error", {offset: "100px"});},
            success : function(data) {
                if (data.result == "success") {
                    parent.layer.msg("操作成功");
                    parent.reLoad();
                    var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                    parent.layer.close(index);
                } else {
                    parent.layer.alert(data.msg, {offset: "100px"})
                }
            }
        });
	}
});

function addPermission(){
	permissions = {
		permissionUser: getArray('permissionUser', 'permissionUserNames'),
		permissionTag: getArray('permissionTag', 'permissionTagNames'),
		permissionOrg: getArray('permissionOrg', 'permissionOrgNames'),
	}
	
    layer.open({
        type : 2,
        title : '添加',
        offset: "0px",
        maxmin : true,
        shadeClose : false, // 点击遮罩关闭层
        area : [ '600px', '500px' ],
        btn: ['确定'],
        yes: function(index, layero){
        	$('#permissionContent').empty();
        	
        	var iframeWindow = window["layui-layer-iframe" + index];
        	var array = iframeWindow.getPermission();
        	
        	var permissionUserIds = array[0];
        	var permissionUserNames = array[1];
        	var permissionTagIds = array[2];
        	var permissionTagNames = array[3];
        	var permissionOfficeIds = array[4];
        	var permissionOrgNames = array[5];
        	
        	var puids = Array.from(permissionUserIds);
        	var ptids = Array.from(permissionTagIds);
        	var poids = Array.from(permissionOfficeIds)
        	puids = puids.toString() != '' ? puids.toString() + "," : "";
        	ptids = ptids.toString() != '' ? ptids.toString() + "," : "";
        	poids = poids.toString() != '' ? poids.toString() + "," : "";
        	
        	$("input[name='permissionUser']").val(puids);
        	$("input[name='permissionTag']").val(ptids);
        	$("input[name='permissionOrg']").val(poids);
        	$("input[name='permissionUserNames']").val(Array.from(permissionUserNames));
        	$("input[name='permissionTagNames']").val(Array.from(permissionTagNames));
        	$("input[name='permissionOrgNames']").val(Array.from(permissionOrgNames));
        	
        	if(permissionUserNames.size > 0 || permissionTagNames.size > 0 || permissionOrgNames.size > 0){
        		$('#permissionEdit').css("display", "inline-block");
        		$('#permissionAdd').css("display", "none");
        	} else {
        		$('#permissionContent').append('<div id="permissionAdd" onclick="addPermission();" style="cursor: pointer; display: block;">点击添加...</div>');
        		$('#permissionAdd').css("display", "block");
        		$('#permissionEdit').css("display", "none");
        	}
        	
        	for(let key of permissionUserNames) {
        		$('#permissionContent').append(createElement(key, "2"));
        	}
        	for(let key of permissionTagNames) {
        		$('#permissionContent').append(createElement(key, "1"));
        	}
        	for(let key of permissionOrgNames) {
        		$('#permissionContent').append(createElement(key, "0"));
        	}
        	
        	layer.close(index);
        },
        content : ctx + 'a/permissionManager/permission'
    });
}

function createElement(name, type){
	if(name == "") return null;
		
	var img = "search-dep.png";
	if(type == "1") img = "tags.png";
	if(type == "2") img = "default_user.png";
	
	var html = 	"<div class='tag-permission-item'>" +
					"<span class='tag-permission-item-left'>" + 
						"<span class='tab-permission-item-head'>" + 
							"<img class='tag-permission-item-img' src='/topview/img/" + img + "'/>" + 
							"<span class='tag-permission-item-name'>" + name + "</span>" + 
						"</span>" + 
						"<span class='tab-permission-item-nbsp'>&nbsp;</span>" + 
					"</span>" + 
				"</div>";
	return html;
}

function getArray(inputId, inputName){
	var objects = Array();
	var ids = $("input[name='"+inputId+"']").val().split(',');
	var names = $("input[name='"+inputName+"']").val().split(',');
	for(let i = 0; i < ids.length; i ++){
		objects.push({id: ids[i], name: names[i], type: '2'});
	}
	return objects;
}